package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.minio.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.OcrUtil;
import com.heima.utils.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.AutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.TesseractException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 霍森彪
 * @date 2022/7/17 13:10
 */
@Service
@Slf4j
@Transactional
public class AutoScanServiceImpl implements AutoScanService {

    @Autowired
    private WmNewsService wmNewsService;

    @Autowired
    private MinIoTemplate minIoTemplate;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private IArticleClient iArticleClient;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;


    @Override
    @Async
    public void autoScanWmNews(Integer newsId) throws Exception {
        if (newsId == null) {
            log.warn("文章审核的入参为空");
            return;
        }
        // 1. 查询wmNews
        WmNews news = wmNewsService.getById(newsId);
        if (news == null) {
            log.warn("新闻" + newsId + "为空");
            return;
        }
        //提取文字
        String text = getText(news.getTitle(), news.getContent());

        //提取图片
        List<byte[]> images = getImages(news.getImages(), news.getContent());

        //OCR提取图片中的文字
        String imageText = getImageText(images);
        text = text + "_"+imageText;

        //使用自定义敏感词检测
        Boolean checkResult = myTextCheck(text);
        if (!checkResult){
            log.warn("自定义文字审核未通过");
            return;
        }



        //调用阿里云审核
        if (StringUtils.isNotEmpty(text)){
            Boolean textResult = checkText(text, news);
            if (!textResult){
                log.warn("文字审核未通过");
                return;
            }
        }

        //调用阿里云图片审核
        if (!CollectionUtils.isEmpty(images)){
            Boolean imageResult = checkImage(images, news);
            if (!imageResult){
                log.warn("图片审核未通过");
                return;
            }
        }

        //ArticleClient远程调用
        ArticleDto articleDto = WmNews2ArticleDto(news);
        ResponseResult responseResult = iArticleClient.saveArticle(articleDto);
        Integer code = responseResult.getCode();
        if (code != 200) {
            log.warn("保存文章失败");
            return;
        }
        Long articleId = (Long) responseResult.getData();
        // 7. 回写wmNews状态和ArticleId
        updateNews(newsId, 9, "通过", articleId);
    }



    //提取文字
    String getText(String title, String content) {
        // 1. 将content转为List<Map>
        List<Map> maps = JSON.parseArray(content, Map.class);
        if (CollectionUtils.isEmpty(maps)) {
            log.warn("content内容为空");
            return title;
        }

        StringBuilder builder = new StringBuilder();

        // 2. 提取content里面的文字部分
        for (Map map : maps) {
            if (CollectionUtils.isEmpty(map)) {
                continue;
            }

            Object type = map.get("type");
            if ("text".equals(type)) {
                String value = (String) map.get("value");
                builder.append(value);
            }
        }

        // 3. 将content的文字和title进行组装
        builder.append("_").append(title);

        // 4. 返回结果
        return builder.toString();
    }

    //提取图片
    List<byte[]> getImages(String images, String content) {

        //要返回的全部图片集合
        ArrayList<String> list = new ArrayList<>();

        if (StringUtils.isNotBlank(images)) {
            String[] split = images.split(",");
            List<String> imagesList = Arrays.asList(split);
            list.addAll(imagesList);
        }

        if (StringUtils.isNotBlank(content)) {
            List<Map> maps = JSON.parseArray(content, Map.class);
            ArrayList<String> imageList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(maps)) {
                for (Map map : maps) {
                    if (!CollectionUtils.isEmpty(map)) {
                        //获取类型
                        Object type = map.get("type");
                        if ("image".equals(type)) {
                            String url = (String) map.get("value");
                            imageList.add(url);
                        }
                    }
                }
                list.addAll(imageList);
            }
        }
        // 4. 把上面两组图片地址 合并在一起
        ArrayList<byte[]> result = new ArrayList<>();
        for (String s : list) {
            if (StringUtils.isEmpty(s)) {
                continue;
            }
            // 5. 借助minIO的download将string转为byte[]
            byte[] bytes = minIoTemplate.downLoadFile(s);
            result.add(bytes);
        }
        // 6. 组装byte[]集合，并返回
        return result;
    }

    ////调用阿里云文字审核
    Boolean checkText(String text,WmNews news) throws Exception {
        //返回的map里面有一个结果,叫suggestion
        Map map = greenTextScan.greeTextScan(text);

        //获取检验结果
        String suggestion = (String) map.get("suggestion");
        if (!StringUtils.isEmpty(suggestion)){
            if ("pass".equals(suggestion)){
                news.setStatus((short)9);
                wmNewsMapper.updateById(news);
            }else if ("block".equals(suggestion)){
                news.setStatus((short)2);
                wmNewsMapper.updateById(news);
            }else{
                news.setStatus((short)3);
                wmNewsMapper.updateById(news);
            }
        }else {
            return false;
        }
        return true;
    }

    //调用阿里云图片审核
    Boolean checkImage(List<byte[]> imagesList,WmNews news) throws Exception {
        Map map = greenImageScan.imageScan(imagesList);
        //获取检验结果
        String suggestion = (String) map.get("suggestion");
        if (!StringUtils.isEmpty(suggestion)){
            if ("pass".equals(suggestion)){
                news.setStatus((short)9);
                wmNewsMapper.updateById(news);
            }else if ("block".equals(suggestion)){
                news.setStatus((short)2);
                wmNewsMapper.updateById(news);
            }else{
                news.setStatus((short)3);
                wmNewsMapper.updateById(news);
            }
        }else {
            return false;
        }
        return true;
    }

    //WmNews转化为ArticleDto\
    @Override
    public ArticleDto WmNews2ArticleDto(WmNews news){
        if (news == null) {
            return null;
        }

        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(news, dto);

        // 处理差异字段
        Integer userId = news.getUserId();
        dto.setAuthorId(userId.longValue());
        WmUser wmUser = wmUserMapper.selectById(userId);
        if (wmUser != null) {
            dto.setAuthorName(wmUser.getName());
        }

        // 获取频道信息
        Integer channelId = news.getChannelId();
        WmChannel wmChannel = wmChannelMapper.selectById(channelId);
        if (wmChannel != null) {
            dto.setChannelName(wmChannel.getName());
        }

        // 布局方式
        dto.setLayout(news.getType());
        dto.setCreatedTime(new Date());

        return dto;
    }

    //回写wmNews状态和ArticleId
    private void updateNews(Integer newsId, Integer status, String reason, Long articleId) {
        WmNews wmNews = new WmNews();
        wmNews.setId(newsId);
        wmNews.setReason(reason);
        wmNews.setStatus(status.shortValue());
        wmNews.setArticleId(articleId);
        wmNewsService.updateById(wmNews);
    }

    //使用自定义敏感词检测
    Boolean myTextCheck(String text){
        if (StringUtils.isBlank(text)){
            //为空说明没有敏感词,返回true
            return true;
        }
        //到mysql中查找所有的敏感词
        QueryWrapper<WmSensitive> wrapper = new QueryWrapper<>();
        wrapper.select("sensitives");
        List<WmSensitive> sensitiveList = wmSensitiveMapper.selectList(wrapper);

        //调用DFA算法,进行敏感词初始化
        List<String> words = sensitiveList.stream().filter(Objects::nonNull).map(WmSensitive::getSensitives).collect(Collectors.toList());
        SensitiveWordUtil.initMap(words);

        //调用DFA算法,进行敏感词匹配
        Map<String, Integer> result = SensitiveWordUtil.matchWords(text);

        //将匹配结果以boolean形式返回
        return CollectionUtils.isEmpty(result);
    }

    //OCR提取图片中的文字
    String getImageText(List<byte[]> image) throws IOException, TesseractException {
        if (CollectionUtils.isEmpty(image)){
            return "";
        }
        StringBuilder builder = new StringBuilder();
        //遍历集合图片
        for (byte[] bytes : image) {
            //把byte[]转成BufferImage
            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            BufferedImage read = ImageIO.read(inputStream);
            //当前图片包含的文字信息
            String textFromImage = OcrUtil.doOcr(read);
            builder.append("_").append(textFromImage);
        }
        return builder.toString();
    }
}
